package cn.iocoder.yudao.framework.common.util.entiy;


import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangsong
 * @date 2021/8/19 14:02
 */
public class BeanUtils{

    public static Map<String,Object> toMap(Object bean) throws Exception{
        return toMap(bean,true);
    }

    /**
     * 实体类转Map
     * @param bean 实体类
     * @param isComplete 是否所有字段全部转换 true:所有私有字段 false:ToField注解字段。
     * @return
     */
    public static Map<String,Object> toMap(Object bean,boolean isComplete) throws Exception{
        Map<String,Object> map = new HashMap<>();
        Class clazz = bean.getClass();
        Field[] fields = ReflexUtils.getDeclaredFields(clazz);
        for(Field field : fields){
            field.setAccessible(true);
            ToField toField = field.getAnnotation(ToField.class);
            Object value = field.get(bean);
            if(value ==null){
                continue;
            }
            if(toField != null){
                String[] names = toField.value();
                if(names!=null && names.length>0){
                    for(String name : names){
                        map.put(name,value);
                    }
                }else{
                    String name = field.getName();
                    map.put(name,value);
                }
            }else{
                if(!isComplete)
                    continue;
                String name = field.getName();
                map.put(name,value);
            }
        }
        return map;
    }

    public static void main(String[] args) {
        Entity entity = Entity.builder()
                .id(1)
                .name("ws")
                .desc("I'm iron man")
                .address("北京市房山区").build();

        try {
            Map<String,Object> map = toMap(entity);
            for(String key : map.keySet()){
                System.out.println(key+"=="+map.get(key));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
